import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  DefaultValuePipe,
  ParseIntPipe,
  Res,
} from '@nestjs/common';
import { WarehouseService } from 'src/service/warehouse.service';
import { CreateWarehouseDto } from 'src/dto/create-warehouse.dto';
import { UpdateWarehouseDto } from 'src/dto/update-warehouse.dto';
import { QueryWarehouseDto } from 'src/dto/query-warehouse.dto';
import { ExcelService } from 'src/common/excel/excel.service';

import * as ExcelJS from 'exceljs';
import * as path from 'path';
import axios from 'axios';
import * as dayjs from 'dayjs';

@Controller('admin/warehouse')
export class WarehouseController {
  constructor(
    private readonly warehouseService: WarehouseService,
    private readonly excelService: ExcelService,
  ) {}

  @Post()
  create(@Body() createWarehouseDto: CreateWarehouseDto) {
    return this.warehouseService.create(createWarehouseDto);
  }

  @Get()
  query(@Query() query: QueryWarehouseDto) {
    return this.warehouseService.query(query);
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.warehouseService.findOne(+id);
  }

  @Patch(':id')
  update(
    @Param('id') id: string,
    @Body() updateWarehouseDto: UpdateWarehouseDto,
  ) {
    return this.warehouseService.update(+id, updateWarehouseDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.warehouseService.remove(+id);
  }

  @Post('export')
  async exportExcel(@Body('id') id: number) {
    let warehouse = await this.warehouseService.findOne(id);

    let list = await this.warehouseService.exportExcel(id);

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Sheet 1');

    // 设置表头
    worksheet.columns = [
      { header: '箱号', key: 'name', width: 20 },
      { header: '装箱个数', key: 'boxNumber', width: 10 },
      { header: '状态', key: 'status', width: 10 },
      { header: '商品名称', key: 'mercadoproductName', width: 10 },
      { header: 'SKU名称', key: 'mercadoskuName', width: 10 },
      { header: '美客多编号', key: 'mercadoskuMercadoNumber', width: 10 },
      { header: 'sku图', key: 'mercadoskuImage', width: 30 },
    ];

    // 添加数据
    list.forEach(async (item, index) => {
      let tableRow = {
        name: item.name,
        boxNumber: item.boxNumber,
        status: item.status == 1 ? '已抵达海外仓' : '运输中',
        mercadoproductName: item.mercadoproduct.name,
        mercadoskuName: item.mercadosku.name,
        mercadoskuMercadoNumber: item.mercadosku.mercadoNumber,
      };

      let mercadoskuImage = item.mercadosku.image;
      console.log('mercadoskuImage', mercadoskuImage);

      worksheet.addRow(tableRow);

      // if (mercadoskuImage) {
      //   try {
      //     let data = await axios
      //       .get(mercadoskuImage, { responseType: 'arraybuffer' })
      //       .then((response) => {
      //         return response.data;
      //       });

      //     console.log('data.length', data.length);

      //     // let buffer = Buffer.from(data);
      //     let base64String = `data:image/png;base64,${Buffer.from(data).toString('base64')}`;

      //     let imageId = workbook.addImage({
      //       base64: base64String,
      //       extension: 'png',
      //     });
      //     worksheet.addImage(imageId, {
      //       tl: { col: 7, row: index + 1 }, // 图片起始位置，第 4 列（从 0 开始计数），当前行
      //       ext: { width: 30, height: 30 }, // 图片尺寸
      //     });
      //   } catch (error) {
      //     console.log('error', error);
      //   }
      // }
    });

    let fileName = dayjs().format('YYYYMMDD') + warehouse.name + '库存';
    // 定义保存路径
    const filePath = path.join(__dirname, '../../public', fileName + '.xlsx');

    try {
      // 写入文件
      await workbook.xlsx.writeFile(filePath);
      return `${process.env.BASE_REQUEST_URL}/${fileName}.xlsx`;
    } catch (error) {
      console.error('保存 Excel 文件时出错:', error);
      throw error;
    }
  }
}
